package com.xinxing.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinxing.learning.security.filter.LoginFilter;
import com.xinxing.learning.security.filter.ParameterFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;

import java.util.HashMap;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final ParameterFilter parameterFilter;

    public SecurityConfig(ParameterFilter parameterFilter) {
        System.out.println(parameterFilter);
        this.parameterFilter = parameterFilter;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        return inMemoryUserDetailsManager;
    }


    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setUsernameParameter("username");
        loginFilter.setPasswordParameter("password");
        loginFilter.setAuthenticationManager(authenticationManagerBean());

        // 认证成功后的处理 返回处理成功的json
        loginFilter.setAuthenticationSuccessHandler((req, resp, authentication) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录成功");
            result.put("status", HttpStatus.OK.value());
            result.put("authentication", authentication);
            resp.setContentType("application/json;charset=UTF-8");
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationSuccess() returned: " + resultStr);
            resp.getWriter().println(resultStr);
        });
        // 认证失败后的处理 返回处理失败后的json
        loginFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录失败: " + ex.getMessage());
            result.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationFailure() returned: " + resultStr);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().println(resultStr);
        });
        return loginFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "请先登录");
                    result.put("status", HttpStatus.UNAUTHORIZED.value());
                    response.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    response.getWriter().println(resultStr);
                })
                .and()
                .logout()
                .logoutSuccessHandler((request, response, authentication) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "注销成功");
                    result.put("status", 200);
                    result.put("authentication", authentication);
                    response.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    response.getWriter().println(resultStr);
                })
                .and()
                .csrf()
                // 将cookie保存到cookie中 并允许前段从cookie中获取csrf令牌
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        ;

        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(parameterFilter, CsrfFilter.class);
    }
}
